package jmind.core.redis;

import jmind.base.lang.IProperties;
import jmind.base.util.DataUtil;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.commands.JedisClusterCommands;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RedisCluster extends AbstractJedis {
    JedisCluster jc;

    /**
     * timeout 单位秒
     * @param name
     * @param p
     */
    public RedisCluster(String name, IProperties p) {

        String[] hostAndPort = p.getProperty("redis." + name + ".host").split(",");
        Set<HostAndPort> jedisClusterNodesSet = new HashSet<HostAndPort>();
        for (String hp : hostAndPort) {
            String[] hap = hp.split(":");
            jedisClusterNodesSet.add(new HostAndPort(hap[0], Integer.parseInt(hap[1])));
        }
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(DataUtil.toInt(p.getProperty("redis." + name + ".maxIdle", "10")));
        genericObjectPoolConfig.setMaxTotal(DataUtil.toInt(p.getProperty("redis." + name + ".maxTotal", "10")));
        genericObjectPoolConfig.setMinIdle(DataUtil.toInt(p.getProperty("redis." + name + ".minIdle")));
        String password=p.getProperty("redis."+name+".password");
        // 配置用秒，这里是毫秒
        int timeout=DataUtil.toInt(p.getProperty("redis." + name + ".timeout", "3")) * 1000;
        if(DataUtil.isEmpty(password)){
            jc = new JedisCluster(jedisClusterNodesSet,
                    timeout, DataUtil.toInt(p.getProperty(
                    "redis." + name + ".maxRedirections", "5")), genericObjectPoolConfig);
        }else{
            jc = new JedisCluster(jedisClusterNodesSet,timeout,
                    timeout, DataUtil.toInt(p.getProperty(
                    "redis." + name + ".maxRedirections", "5")),password, genericObjectPoolConfig);
        }


    }

    public void releaseResource() {
            jc.close();


    }

    public void close(Object resource) {

    }

    public long del(String... keys) {
        return jc.del(keys);
    }

    public List<String> mget(String... key) {
        return jc.mget(key);
    }

    @Override
    public JedisClusterCommands getResource() {
        return jc;
    }

}
